package logic

import (
	"context"
	"encoding/json"
	"github.com/google/uuid"
	"recharge_srv/cache"
	"recharge_srv/models"
	"recharge_srv/pkg"
	"time"

	"recharge_srv/internal/svc"
	"recharge_srv/recharge"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddOrderLogic {
	return &AddOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddOrderLogic) AddOrder(in *recharge.AddOrderRequest) (*recharge.AddOrderResponse, error) {
	// todo: add your logic here and delete this line

	var u models.User
	u.ID = uint(in.UserId)
	err := u.ShowUser()
	if err != nil {
		return nil, err
	}
	if u.ID == 0 {
		return nil, err
	}

	var r models.OrderRecharge
	r.UserId = in.UserId
	r.OrderOn = uuid.NewString()
	r.RechargeTIme = time.Now()
	r.Amount = in.Amount
	r.Status = 0
	err = r.CreateOrder()
	if err != nil {
		return nil, err
	}

	var ou models.OrderUser
	ou.RechargeId = int(r.ID)
	ou.PayType = 0
	ou.Status = 1
	err = ou.CreateOrder()
	if err != nil {
		return nil, err
	}

	marshal, err := json.Marshal(ou)
	if err != nil {
		return nil, err
	}

	cache.Rdb.Set(l.ctx, "userRecharge"+u.Mobile, marshal, time.Hour*24)

	alipay := pkg.Alipay(r.OrderOn, float64(in.Amount))

	return &recharge.AddOrderResponse{PayUrl: alipay}, nil
}
